import * as React from 'react';
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { reqUpload } from '../../axios';
export interface MyUploadProps {
    getImageUrl: (imageUrl: string) => void
    imageUrl: string
    updateBackCall ?: ()=>void
}

export interface MyUploadState {

}
function getBase64(img: any, callback: any) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

function beforeUpload(file: any) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}
class MyUpload extends React.Component<MyUploadProps, MyUploadState> {
    state = {
        imageUrl: '',
        loading: false
    }
    componentDidMount() {
        const { imageUrl } = this.props;
        this.setState({ imageUrl });
    }
    //当添加或更改图片时触发
    handleChange = (info: any) => {
        if (info.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj, (imageUrl: any) => {
                this.props.getImageUrl(info.file.response.url);
                this.setState({
                    imageUrl: info.file.response.url,
                    loading: false,
                },()=>{
                    if(this.props.updateBackCall){
                        //需要进行状态的更新
                        this.props.updateBackCall()
                    }
                });
                
            }
            );
        }
    };
    render() {
        const { loading } = this.state;
        const token = window.localStorage.getItem('user') || '';
        const uploadButton = (
            <div>
                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div style={{ marginTop: 8 }}>Upload</div>
            </div>
        );
        return (<div>
            <Upload
                name="file"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                headers={{ Authorization: token }}
                action={reqUpload}
                beforeUpload={beforeUpload}
                onChange={this.handleChange}
            >
                {this.props.imageUrl ? <img src={this.props.imageUrl} alt="avatar" style={{ width: '100%',height:'100%',borderRadius:'50%' }} /> : uploadButton}
            </Upload>
        </div>);
    }
}

export default MyUpload;